//
//  WYLocationViewController.m
//  Withyou
//
//  Created by Handyzzz on 2017/6/12.
//  Copyright © 2017年 Withyou Inc. All rights reserved.
//

#import "MHLocationViewController.h"
#import "MHCommonTableViewCell.h"
//高德地图基础SDK头文件 与key的宏

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "JKRSearchController.h"
#import "MHSearchCircleResultViewController.h"
#import "MHAutoAddressViewController.h"
#import "AMapTipAnnotation.h"
#import "POIAnnotation.h"
#import "MHLocationViewModel.h"
#import "MHCustomTip.h"

@interface MHLocationViewController ()<UITableViewDelegate,UITableViewDataSource,AMapSearchDelegate,AMapLocationManagerDelegate,MAMapViewDelegate,JKRSearchControllerhResultsUpdating,JKRSearchControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *location;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapPOISearchResponse *response;
@property (nonatomic, strong) JKRSearchController *searchController;
@property(nonatomic, strong) MHCustomTip *tip;
@property(nonatomic, strong) MHLocationViewModel *viewModel;
@property(nonatomic, strong) MHCustomTip *pendSearch;
@property(nonatomic, assign) BOOL apendSearch;
@end

@implementation MHLocationViewController
@dynamic viewModel;

-(void)initData{
    
    
    [self startUpdatingLocation];
    [self createMapView];
    self.searchController.searchBar.frame = CGRectMake(15, MH_APPLICATION_TOP_BAR_HEIGHT + 12 , MH_SCREEN_WIDTH - 30, 35);
    self.searchController.searchBar.backgroundImageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.searchController.searchBar];
    
}


-(void) startUpdatingLocation{
    __weak __typeof(self)weakSelf = self;
    [[MHLocationManager sharedInstance] startUpdatingLocationWithBlock:^(CLLocation *location){
        weakSelf.location = location;
        [weakSelf lockPointAnnotationViewWithCoordinate:CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)];
        [[MHLocationManager sharedInstance] searhAroundWithLocation:self.location reslutBlock:^(AMapPOISearchBaseRequest *requst,AMapPOISearchResponse *response) {
//            if (weakSelf.response.count > 0) {
                [weakSelf poiSearchDone:requst response:response];
//            }
            
        }];
        [MHLocationManager uploadLocationToRemote:location];
        [weakSelf.locationManager stopUpdatingLocation];
    }];
}

-(void) createMapView
{
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, MH_APPLICATION_TOP_BAR_HEIGHT, self.view.size.width, self.view.size.height/2 - MH_APPLICATION_TOP_BAR_HEIGHT)];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    self.mapView.zoomLevel = 14.5;
    [self.mapView setMaxZoomLevel:18];
    self.mapView.showsCompass = NO;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    self.mapView.showsUserLocation = YES;
    [self.view addSubview:self.mapView];
}


- (JKRSearchController *)searchController {
    if (!_searchController) {
        MHAutoAddressViewController *resultSearchController = [[MHAutoAddressViewController alloc] init];
        __weak __typeof(self)weakSelf = self;
        resultSearchController.selectCompleteBlock = ^(AMapTip *tip) {
            if(self.viewModel.location)
            {
                 weakSelf.selectIndex = 3;
            }else
            {
                 weakSelf.selectIndex = 1;
            }
           
            [weakSelf clearAndShowAnnotationWithTip:tip];
            [weakSelf.searchController endSearch];
            weakSelf.pendSearch = self.tip;
            weakSelf.apendSearch = YES;
        };
        _searchController = [[JKRSearchController alloc] initWithSearchResultsController:resultSearchController];
        _searchController.searchBar.placeholder = @"搜索地点或地址";
        _searchController.hidesNavigationBarDuringPresentation = YES;
        _searchController.searchResultsUpdater = self;
        _searchController.searchBar.delegate = resultSearchController;
        _searchController.delegate = self;
    }
    return _searchController;
}


#pragma mark - JKRSearchControllerDelegate
- (void)willPresentSearchController:(JKRSearchController *)searchController {
    self.searchController.searchBar.y = MH_APPLICATION_TOP_BAR_HEIGHT/2 - 25/2 ;
    self.searchController.searchBar.backgroundImageView.backgroundColor = MHColorFromHexString(@"#F1F1F2");
}

- (void)didPresentSearchController:(JKRSearchController *)searchController {
}

- (void)willDismissSearchController:(JKRSearchController *)searchController {
     self.searchController.searchBar.y = MH_APPLICATION_TOP_BAR_HEIGHT + 12;
       self.searchController.searchBar.backgroundImageView.backgroundColor = [UIColor whiteColor];
}

- (void)didDismissSearchController:(JKRSearchController *)searchController {
}


#pragma mark - JKRSearchControllerhResultsUpdating
- (void)updateSearchResultsForSearchController:(JKRSearchController *)searchController {
    NSString *searchText = searchController.searchBar.text;
    __weak __typeof(self)weakSelf = self;
    [[MHLocationManager sharedInstance] searhAroundWithKeyWorld:searchText location:self.location reslutBlock:^(AMapPOISearchBaseRequest *requst,AMapPOISearchResponse *response) {
        [weakSelf poiSearchDone:requst response:response];
    }];
    
}


#pragma mark - JKRSearchBarDelegate
- (void)searchBarTextDidBeginEditing:(JKRSearchBar *)searchBar {
    
}

//返回处理
-(void)rightButtonClick
{
    if (self.viewModel.completeBlock && self.tip) {
        if (self.selectIndex == 0) {
            self.tip.isShowLocation = NO;
        }else
        {
            self.tip.isShowLocation = YES;
        }
        
        
        
        self.viewModel.completeBlock(self.tip);
        
        
    }else
    {
        self.viewModel.completeBlock(nil);
    }
    [self.viewModel.services popViewModelAnimated:YES];
    
}
#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
        MAAnnotationView *annView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"userLocationAnnViewID"];
        if (annView == nil) {
            annView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"userLocationAnnViewID"];
            annView.image = nil;
        }
        return annView;
    }else if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *busStopIdentifier = @"districtIdentifier";
        MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:busStopIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                                reuseIdentifier:busStopIdentifier];
        }
        poiAnnotationView.image = [UIImage imageNamed:@"icon_cricle_maplocation"];
        poiAnnotationView.canShowCallout = NO;
        return poiAnnotationView;
    
    }

    return nil;
}



- (void)clear
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
}
- (void)clearAndShowAnnotationWithTip:(MHCustomTip *)tip
{
    /* 清除annotations & overlays */
    [self clear];
    self.tip = tip;
    if (tip.uid != nil && tip.location != nil) /* 可以直接在地图打点  */
    {
        //地图上打点
        [self lockPointAnnotationViewWithCoordinate:CLLocationCoordinate2DMake(tip.location.latitude, tip.location.longitude)];
    }
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth   = 4.f;
        polylineRenderer.strokeColor = [UIColor magentaColor];
        
        return polylineRenderer;
    }
    
    return nil;
}

- (void)poiSearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    
    self.tip = [MHCustomTip createWithAMapPOI:[response.pois firstObject]];
    
    NSMutableArray *pois = [NSMutableArray arrayWithCapacity:response.pois.count];
    NSMutableArray *tips = [NSMutableArray arrayWithCapacity:response.pois.count];
    
   
    
    AMapPOI *noLocationPOI = [[response.pois firstObject] copy];
//    noLocationPOI.name = @"不显示位置";
//    noLocationPOI.address = @"";
    [pois addObject:noLocationPOI];
    
    
    if(self.viewModel.isRecentLocation)
    {
        AMapPOI *cityAear =  [[response.pois firstObject] copy];
        cityAear.name = cityAear.city;
        cityAear.address = @"";
        [pois appendObject:cityAear];
        
        if (self.viewModel.location) {
            AMapPOI *circlePosition =  [AMapPOI new];
            circlePosition.name = self.viewModel.location.areaName;
            circlePosition.address = self.viewModel.location.address;
            circlePosition.adcode = self.viewModel.location.adcode;
            circlePosition.location = [AMapGeoPoint locationWithLatitude:self.viewModel.location.lat longitude:self.viewModel.location.lon];
            circlePosition.citycode = self.viewModel.location.citycode;
            [pois appendObject:circlePosition];
             self.selectIndex = 3;
        }else
        {
            self.selectIndex = 2;
//            self.tip = [MHCustomTip createWithAMapPOI:[response.pois firstObject]];
        }
    }else
    {
        if (response.pois.count >= 1) {
            self.selectIndex = 1;
            self.tip = [MHCustomTip createWithAMapPOI:[response.pois firstObject]];
        }
    }
    
    
    if(self.apendSearch)
    {
        AMapPOI *temp =  [[AMapPOI alloc] init];
        temp.uid = self.pendSearch.uid;
        temp.name = self.pendSearch.name;
        temp.adcode = self.pendSearch.adcode;
        temp.district = self.pendSearch.district;
        temp.address = self.pendSearch.address;
         temp.location = self.pendSearch.location;
        temp.typecode = self.pendSearch.typecode;
        temp.citycode = self.pendSearch.cityCode;
        [pois addObject:temp];
       
    }
    
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
        if (obj.address.length > 0 && (![obj.address isEqualToString:self.pendSearch.address]) && (![obj.address isEqualToString:self.viewModel.location.address])) {
            
            
            [pois addObject:obj];
            
            if (![request isKindOfClass:[AMapPOIAroundSearchRequest class]]) {
               
                MHCustomTip *tip =  [[MHCustomTip alloc] init];
                tip.uid = obj.uid;
                tip.name = obj.name;
                tip.adcode = obj.adcode;
                tip.district = obj.district;
                tip.address = obj.address;
                tip.location = obj.location;
                tip.typecode = obj.typecode;
                tip.cityCode = obj.citycode;
                [tips addObject:tip];
            }
        }else
        {
            if([obj.address isEqualToString:self.viewModel.location.address] && self.viewModel.isRecentLocation)
            {
                self.selectIndex = self.viewModel.location ?  2 : 1;
            }
        }
    }];
    self.pendSearch = nil;
    if ([request isKindOfClass:[AMapPOIAroundSearchRequest class]]) {
        response.pois = pois;
        self.response = response;
        [self.tableView reloadData];
        return;
    }else
    {
        MHAutoAddressViewController *autoVc = (MHAutoAddressViewController *) self.searchController.searchResultsController;
        autoVc.datas = tips;
        [autoVc.tableView reloadData];
    }
    [self.mapView removeAnnotations:self.mapView.annotations];
    
}

-(void) lockPointAnnotationViewWithCoordinate:(CLLocationCoordinate2D )centerCoordinate {
    self.mapView.centerCoordinate  = centerCoordinate;
    MAPointAnnotation *poiAnnotation = [[MAPointAnnotation alloc] init];
    poiAnnotation.coordinate = self.mapView.centerCoordinate;
    [self.mapView addAnnotation:poiAnnotation];
    [poiAnnotation setLockedScreenPoint:CGPointMake(self.mapView.center.x, self.mapView.center.y - 64)];
    [poiAnnotation setLockedToScreen:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setNavigationBar];
    [self creatTableView];
    [[AMapServices sharedServices] setEnableHTTPS:YES];
    //高德地图的key
    [self initData];
    
}

-(UITableView*)creatTableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.height/2, self.view.width, self.view.height/2) style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.sectionIndexColor = [UIColor blueColor];
        _tableView.sectionIndexTrackingBackgroundColor = UIColorHex(@"#f5f5f5");
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 56.f;
        _tableView.tableHeaderView.hidden = NO;
        [_tableView registerClass:[MHCommonTableViewCell class] forCellReuseIdentifier:@"MHCommonTableViewCell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

#pragma delegate and Datasource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _response.pois.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MHCommonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MHCommonTableViewCell" forIndexPath:indexPath];
    if(indexPath.row == 0)
    {
        cell.textLabel.text = @"不显示位置";
    }else
    {
        cell.textLabel.text = ((AMapPOI*)_response.pois[indexPath.row]).name;
        cell.descriptionLabel.text = ((AMapPOI*)_response.pois[indexPath.row]).address;
    }
    
    if (indexPath.row == self.selectIndex) {
        cell.rightImageView.hidden  = NO;
    }else
    {
         cell.rightImageView.hidden  = YES;
    }

    if (indexPath.row == 0) {
        cell.needChangeFrame = YES;
    }else
    {
        if (self.viewModel.location && indexPath.row == 1 ) {
            cell.needChangeFrame = YES;
        }else
        {
            cell.needChangeFrame = NO;
        }
    }
    return cell;
}


- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction {
    
    //先赋值，再移动，然后是搜索结果，清空;
    if(!wasUserAction && self.pendSearch == nil)
    {
        return;
    }
    
    NSArray *anoti = mapView.annotations;
    if (self.pendSearch) {
        if(self.viewModel.isRecentLocation)
        {
           self.selectIndex = self.viewModel.location ? 3 : 2;
        }else
        {
            self.selectIndex = 1;
        }
        
    }else
    {
        self.selectIndex = 1;
        self.apendSearch = NO;
    }

    for (MAPointAnnotation *annotation in anoti) {
        if (![annotation.title isEqualToString:@"当前位置"]) {
            __weak __typeof(self)weakSelf = self;
            CLLocation *location = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
            [[MHLocationManager sharedInstance] searhAroundWithLocation:location reslutBlock:^(AMapPOISearchBaseRequest *requst,AMapPOISearchResponse *response) {
                [weakSelf poiSearchDone:requst response:response];
            }];
            
            return;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.selectIndex = indexPath.row;
    [self.tableView reloadData];
    AMapPOI *poi = self.response.pois[indexPath.row];
    MHCustomTip *tip =  [[MHCustomTip alloc] init];
    tip.uid = poi.uid;
    tip.name = poi.name;
    tip.adcode = poi.adcode;
    tip.district = poi.district;
    tip.address = poi.address;
    tip.location = poi.location;
    tip.typecode = poi.typecode;
    tip.cityCode = poi.citycode;
    self.tip = tip;
    [self clearAndShowAnnotationWithTip:tip];
    
    
    if (self.viewModel.isRecentLocation) {
        if (self.selectIndex == 1)
        {
            [[MHLocationManager sharedInstance] geocodeSearchWithAddress:self.tip.name geoBlock:^(AMapGeocodeSearchResponse *response) {
                if (response.geocodes.count == 0)
                {
                    return;
                }
               AMapGeocode *code = response.geocodes.firstObject;
                tip.cityCode = code.citycode;
                tip.adcode = code.adcode;
                tip.district = code.district;
                tip.location = code.location;

            }];
        }
    }
}

@end
